﻿IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RemoveDirectoryEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[RemoveDirectoryEntry]
GO

CREATE PROCEDURE [dbo].[RemoveDirectoryEntry]
	@UserRoles TNVarCharSet READONLY,
	@PathOrId nvarchar(MAX),
	@SkipCutSubsets INT = 0
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @Id bigint
	
	EXEC GetDirectoryEntryId @PathOrId, 0, @Id = @Id OUTPUT
	
	IF @Id IS NULL RETURN 1

	DECLARE @Type int
	
	SELECT @Type = [Type]
	FROM DirectoryEntry
	WHERE Id = @Id

	IF @Type IS NULL RETURN 1

	IF dbo.HasPermission(@UserRoles, @Id, 2) = 0 RETURN 2

/*--SpecificDeletes--*/

	DELETE FROM AccessControlList
	WHERE DirectoryEntryId = @Id
	
	IF @SkipCutSubsets = 0
		EXEC dbo.CutEmptySubsets @DeletedId = @Id

	DELETE FROM DirectoryEntry
	WHERE Id = @Id
	
	DECLARE @Children TBigIntSet
	
	INSERT INTO @Children(Value)
	SELECT Id
	FROM DirectoryEntry WHERE ParentId = @Id
	
	DECLARE Cur CURSOR LOCAL
		FOR SELECT Value FROM @Children
	
	OPEN Cur
	
	WHILE 1 = 1
	BEGIN
		FETCH NEXT FROM Cur INTO @Id
		
		IF @@FETCH_STATUS <> 0 BREAK

		DECLARE @ChildId nvarchar(max) = '#' + CAST(@Id as nvarchar(max))

		EXEC dbo.RemoveDirectoryEntry @UserRoles, @ChildId, 1
	END
	
	CLOSE Cur

	RETURN 0
END
GO